package net.androy.smugmugtool;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import net.androy.smugmugtool.SearchActivity.ImageAdapter;
import net.androy.smugmugtool.vo.SearchResult;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

public class SmugMugRetriever implements Runnable {

    private SearchActivity activity = null;
    private String SEARCHURL = "http://api.smugmug.com/hack/feed.mg?Type=keyword&format=rss&ImageCount=20&Size=Small&Data=";
    private String ALLTIME = "http://api.smugmug.com/hack/feed.mg?Type=popular&format=rss&ImageCount=20&Size=Small&Data=all";
    private String TODAY = "http://api.smugmug.com/hack/feed.mg?Type=popular&format=rss&ImageCount=20&Size=Small&Data=today";
    
    public SmugMugRetriever(SearchActivity activity) {
	this.activity = activity;
    }

    public void run() {
	HttpUriRequest request = null;
	HttpResponse response = null;
	InputStream is = null;
	XMLReader reader = activity.getReader();
	final List images = activity.getImages();
	final List<Bitmap> bitmaps = activity.getBitmaps();
	final ArrayAdapter<ImageView> adapter = activity.getAdapter();

	DefaultHttpClient client = new DefaultHttpClient();

	try {
	    //request = new HttpGet("http://api.smugmug.com/hack/feed.mg?Type=popular&Data=today&ImageCount=20&format=rss&Size=Small");
	    String mode = activity.getMode();
	    if(mode.equals("SEARCH")){
		request = new HttpGet(SEARCHURL+activity.getKeyword());	
	    }else if(mode.equals("ALLTIME")){
		request = new HttpGet(ALLTIME);
	    }else if(mode.equals("TODAY")){
		request = new HttpGet(TODAY);
	    }
	    

	    // request = new
	    // HttpGet("http://www.wanderingoak.net/stations.xml");

	    response = client.execute(request);
	    HttpEntity entity = response.getEntity();
	    is = entity.getContent();
	    reader.parse(new InputSource(is));
	    
	    for(int i= 0 ; i< images.size(); i++){
		Log.d("Image:::: ", ((SearchResult)images.get(i)).getTitle());
		Log.d("Image:::: ", ((SearchResult)images.get(i)).getGuid());
	    }

	    try {
		for (int i = 0; i < images.size(); i++) {
		    ImageView iv = new ImageView(activity);
		    try {
			
			SearchResult result = (SearchResult) images.get(i);
			
			Log.i("Display", "=================================");
			Log.i("Display", result.getGuid());
			Log.i("Display", "=================================");
			URL aURL = new URL(result.getGuid());
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is2 = conn.getInputStream();
			/*
			 * Buffered is always good for a performance plus.
			 */
			BufferedInputStream bis = new BufferedInputStream(is2, 16384);
			/* Decode url-data to a bitmap. */
			Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is2.close();
			bitmaps.add(bm);
			
			if(i > 0 && i % 5 == 0){
			    activity.getMHandler().post(new Runnable() {
				public void run() {
				    ImageAdapter ia = (ImageAdapter) activity.getG()
					    .getAdapter();
				    ia.notifyDataSetChanged();
				}
			    });
			}
			// activity.getG().addView(iv, 136, 88);
		    } catch (IOException e) {
			Log.e("DEBUGTAG", "Remtoe Image Exception", e);
		    }
		}

	    } catch (Exception e) {
		e.printStackTrace();
	    }

	    is.close();
	    
	    
	    activity.getMHandler().post(new Runnable() {
		public void run() {
		    activity.setProgressBarIndeterminateVisibility(false);
		}
	    });

	} catch (Exception e) {
	    e.printStackTrace();
	    Log.e("SmugMug on Start", e.getMessage());
	}

    }
}
